package side_panel

import (
	"fmt"
	"strings"

	"file_explorer/view/store"

	"fyne.io/fyne/v2/theme"
	"fyne.io/fyne/v2/widget"
	jsoniter "github.com/json-iterator/go"
)

const (
	projectName = "file_explorer"
)

type LogPanel struct {
	clearButton *widget.Button
	entry       *widget.Entry
	lines       []string

	gCtx *store.GlobalContext
}

type logInfo struct {
	Level   string `json:"level"`
	Time    string `json:"time"`
	Caller  string `json:"caller"`
	Message string `json:"message"`
}

func (info *logInfo) toString() string {
	return fmt.Sprintf("[%s] %s %s %s",
		info.Level,
		info.Time,
		info.Caller,
		info.Message,
	)
}

func (panel *LogPanel) format(bytes []byte) string {
	line := &logInfo{}
	jsoniter.Unmarshal(bytes, line)

	line.Level = strings.ToUpper(line.Level)
	line.Caller = line.Caller[strings.LastIndex(line.Caller, projectName)+len(projectName)+1:]

	return line.toString()
}

func (panel *LogPanel) Write(bytes []byte) (n int, err error) {
	line := panel.format(bytes)
	panel.lines = append(panel.lines, line)
	if len(panel.lines) > panel.gCtx.GetGlobalConf().LogRowNum {
		panel.lines = panel.lines[1:]
	}
	panel.entry.Text = strings.Join(panel.lines, "\n") + "\n"
	panel.entry.CursorRow = len(panel.lines) + 1
	panel.entry.Refresh()

	return len(bytes), nil
}

func (panel *LogPanel) GetClearButton() *widget.Button {
	if panel.clearButton == nil {
		panel.clearButton = widget.NewButtonWithIcon("清空", theme.CancelIcon(), func() {
			panel.lines = nil
			panel.entry.Text = ""
			panel.entry.CursorRow = 0
			panel.entry.Refresh()
		})
	}
	return panel.clearButton
}

func (panel *LogPanel) GetEntry() *widget.Entry {
	return panel.entry
}

func newLogPanel(gCtx *store.GlobalContext) *LogPanel {
	panel := &LogPanel{
		entry: widget.NewEntry(),
		gCtx:  gCtx,
	}

	return panel
}
